package thread.demo.delayQueue;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

// 此类表示 延迟队列任务
class DelayQueueTask implements Delayed {
  
  /* 任务名称 */
  private String name;
  /* 延迟时间 */
  public Long delayTime;
  
  public DelayQueueTask(String name, Long delayTime) {
    this.name = name;
    this.delayTime = System.currentTimeMillis() + delayTime * 1000;
  }
  
  // 这个方法可以判断 延迟时间是否过期
  @Override
  public long getDelay(TimeUnit unit) {
    return unit.toNanos(this.delayTime - System.currentTimeMillis());
  }
  
  @Override
  public int compareTo(Delayed o) {
    DelayQueueTask task = (DelayQueueTask) o;
    return (int) (this.delayTime - task.delayTime);
  }
  
  @Override
  public String toString() {
    return "DelayQueueTask{" + "name='" + name + '\'' + ", delayTime=" + delayTime + '}';
  }
}

public class DelayQueueTest001 {
  public static void main(String[] args) throws InterruptedException {
    DelayQueue<DelayQueueTask> queue = new DelayQueue<>();
    
    queue.add(new DelayQueueTask("d", 10L));
    queue.offer(new DelayQueueTask("a", 11L));
    queue.offer(new DelayQueueTask("b", 5L));
    queue.offer(new DelayQueueTask("c", 8L));
    
    new Thread(() -> {
      queue.offer(new DelayQueueTask("e", 2L));
    }).start();
    
    System.out.println(queue.take());
    System.out.println(queue.take());
    System.out.println(queue.take());
    System.out.println(queue.take());
    System.out.println(queue.take());
  }
}
